<template>
  <el-card class="artical-add-container">
    <div slot="header" class="header">
      <!-- 文章预置项表单-->
      <el-form
        ref="article"
        :model="article"
        label-width="80px"
        style="width: 20%"
      >
        <el-form-item label="文章标题:">
          <el-input
            v-model="article.title"
            placeholder="请填写文章标题:"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章归类:">
          <el-select v-model="article.categoryId" placeholder="请选择文章类别">
            <el-option
              v-for="item in categorys"
              :key="item.id"
              :label="item.category_name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否推荐:" prop="delivery">
          <el-switch v-model="article.isRecommend"></el-switch>
        </el-form-item>
      </el-form>
      <!-- 文章描述表单 -->
      <el-form
        ref="article"
        :model="article"
        label-width="80px"
        style="width: 40%"
      >
        <el-form-item label="文章描述:">
          <el-input
            type="textarea"
            v-model="article.description"
            rows="8"
            placeholder="请填写文章描述"
          ></el-input>
        </el-form-item>
      </el-form>
      <!-- 文章封面上传 -->
      <el-upload
        class="uploader"
        name="coverPicture"
        action="http://localhost:3000/upload/coverPicture/"
        :show-file-list="true"
        :limit="1"
        :on-exceed="handleImageExeed"
        :before-upload="beforeImageUpload"
        :on-success="handleSuccessUpload"
      >
        <img
          v-if="imageUrl"
          :src="imageUrl"
          class="picture"
          style="width: 100%"
        />
        <i v-else class="uploader-tip">点击添加文章封面 </i>
      </el-upload>
    </div>
    <div class="button">
      <el-button type="primary" @click="handleUpdate">更新</el-button>
    </div>
    <div class="main">
      <!-- 富文本编辑器-双向数据绑定 -->
      <quill-editor
        :options="editorOption"
        :content="article.content"
        @change="onEditorChange($event)"
        style="width: 100%"
      >
      </quill-editor>
    </div>
  </el-card>
</template>

<script>
export default {
  name: 'ArticleUpdate',
  data() {
    return {
      article: {
        title: '',
        description: '',
        categoryId: '',
        isRecommend: false,
        coverPicture: '',
        content: '',
      },
      imageUrl: '',
      categorys: [],
      editorOption: {
        // quill模块配置项,可以修改和扩展富文本编辑器的功能
      },
    }
  },
  methods: {
    handleUpdate() {
      let id = this.$route.query.id
      let newArticle = {
        title: this.article.title,
        cover_picture: this.article.coverPicture,
        description: this.article.description,
        content: this.article.content,
        category_id: this.article.categoryId,
        is_recommend: this.article.isRecommend ? 1 : 0,
      }
      //给提示框后确认更新文章
      this.$confirm('此操作将确认更新该篇文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http.put(`/articles/?id=${id}`, newArticle).then((res) => {
            if (res.code == 0) {
              this.$router.push('/home/article')
              this.$message({
                type: 'success',
                message: '更新成功!',
              })
            } else {
              // console.log(res.msg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消更新',
          })
        })
    },
    // 富文本输入改变处理函数
    onEditorChange({ quill, html, text }) {
      this.article.content = html
    },
    // 封面图片上传处理函数
    handleSuccessUpload(res, file, fileList) {
      this.imageUrl = res.result.path
      this.article.coverPicture = res.result.path
    },
    handleImageExeed(files, fileList) {
      if (files.length === 1) {
        this.$message.error('只能上传一张图片')
      }
    },
    beforeImageUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 5
      if (['image/jpeg', 'image/jpg', 'image/png'].indexOf(file.type) === -1) {
        this.$message.error('上传头像图片只能是 JPG , PNG , JPEG 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 5MB!')
        return false
      }
    },
  },
  created() {
    // 当前文章的id this.$route.query.id
    // 获取单篇文章
    this.$http.get(`/articles?id=${this.$route.query.id}`).then((res) => {
      if (res.code == 0) {
        this.article.title = res.result[0].title
        this.article.description = res.result[0].description
        this.article.categoryId = res.result[0].category_id
        this.article.isRecommend = res.result[0].is_recommend ? true : false
        this.article.coverPicture = res.result[0].cover_picture
        this.article.content = res.result[0].content
        // this.imageUrl实现加载页面时回显图片,如果数据库中没有图片的网络地址(下载地址)时,
        // 给一个默认的图片网络地址"/download/coverPicture/?id=default"
        this.imageUrl =
          res.result[0].cover_picture.indexOf('/download/coverPicture') == -1
            ? '/download/coverPicture/?id=default'
            : res.result[0].cover_picture
      } else {
        // console.log(res.msg)
      }
    })
    // 获取全部分类
    this.$http.get('/categorys').then((res) => {
      if (res.code == 0) {
        this.categorys = res.result
      } else {
        // console.log(res.msg)
      }
    })
  },
}
</script>

<style lang="stylus">
// 引入主题配色
@import "styles/theme.styl";
.artical-add-container
  .header
    display: flex
    justify-content: space-between
    .el-upload
      width: 200px
      height: 180px
      border: 1px solid #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      .uploader-tip
        font-size: 16px;
        color: #ccc9db;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      .picture
        width: 178px;
        height: 178px;
        display: block;
  .main
    display: flex
    justify-content: space-between
    .quill-editor
      margin-bottom: 40px
  .button
    display: flex
    justify-content:left
    margin-bottom: 20px
</style>
<style>
textarea {
  min-height: 180px;
}
</style>
